<template>
  <!-- 表单收集页 -->
  <el-dialog v-model="dialogVisible" title="新建业务" width="1000">
    <div style="display: flex; justify-content: center; align-items: center;margin: 20px 0;">
      <el-form :model="addOperationInfo" label-position="left" label-width="auto" size="large" style="width: 800px"
        :rules="rules" ref="formDom">
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="addOperationInfo.businessName" placeholder="填写业务名称" />
        </el-form-item>
        <el-form-item label="公司归属" prop="companyId">
          <el-input v-model="addOperationInfo.companyId" placeholder="填写公司Id" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="addOperationInfo.longitude" placeholder="填写经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="addOperationInfo.latitude" placeholder="填写纬度" />
        </el-form-item>
        <el-form-item label="城市" prop="cityCode">
          <el-input v-model="addOperationInfo.cityCode" placeholder="填写城市代号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-segmented v-model="addOperationInfo.status" :options="Status" />
        </el-form-item>
        <el-form-item label="描述" style="width: 570px;" prop="description">
          <el-input v-model="addOperationInfo.description" type="textarea" />
        </el-form-item>
        <el-form-item label="业务图标" style="width: 570px;" prop="description">
          <el-upload class="upload-demo" action="#" ref="uploadRef" :auto-upload="false" limit=1
            accept=".png,.jpeg,.jpg" :before-upload="uploadPreview" :http-request="upLoadFile" list-type="picture">
            <template #trigger>
              <el-button type="primary">选择图片</el-button>
            </template>
            <el-button class="ml-3" type="success" @click="submitUpload" style="margin-left: 5px;">
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                图片大小不能大于5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: center; align-items: center;">
        <el-button type="primary" @click="addOperationToRemote">
          提交
        </el-button>
        <el-button type="primary" @click="resetForm">
          清空
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div class="container">
    <div class="body">
      <div class="box">
        <!-- 收集页唤出按键 -->
        <div class="topBtns">
          <el-button type="primary" class="topBtn" @click="showDialog">新建业务</el-button>
          <el-button type="primary" class="topBtn" @click="refresh">刷新</el-button>
        </div>
        <!-- 内容展示 -->
        <div class="contents">
          <div class="content">
            <el-table :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
              :data="operationArr.slice(pageSize * (pageNo - 1), pageSize)" style="width: 100%;height: 650px;"
              max-height="600px" fit="false">
              <el-table-column prop="id" label="业务id" width="150" />
              <el-table-column prop="businessName" label="业务名称/name" width="150">
                <template #default="scope">
                  <div v-if="!scope.row.isEdit">{{ scope.row.businessName }}</div>
                  <el-input v-else v-model="scope.row.businessName" placeholder="请输入业务名称" />
                </template>
              </el-table-column>
              <el-table-column prop="companyName" label="公司/company" width="150" />
              <el-table-column prop="description" label="描述/description" width="200">
                <template #default="scope">
                  <div v-if="!scope.row.isEdit">{{ scope.row.description }}</div>
                  <el-input v-else v-model="scope.row.description" type="textarea" placeholder="请输入描述" />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态/status" width="120" :formatter="statusMap">
                <template #default="scope">
                  <div v-if="!scope.row.isEdit">{{ statusMap(scope.row) }}</div>
                  <el-select v-else v-model="scope.row.status" placeholder="请选择状态">
                    <el-option v-for="status in Status" :value="getNoByStatus(status)" :label="status"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="longitude" label="经度/longitude" width="150">
                <template #default="scope">
                  <div v-if="!scope.row.isEdit">{{ scope.row.longitude }}</div>
                  <el-input v-else v-model="scope.row.longitude" placeholder="请输入经度" />
                </template>
              </el-table-column>
              <el-table-column prop="latitude" label="纬度/latitude" width="200">
                <template #default="scope">
                  <div v-if="!scope.row.isEdit">{{ scope.row.latitude }}</div>
                  <el-input v-else v-model="scope.row.latitude" placeholder="请输入纬度" />
                </template>
              </el-table-column>
              <el-table-column prop="imageUrl" label="业务logo" width="200" :show-overflow-tooltip="true">
                <template #default="scope">
                  <el-image style="width: 100%; height: 50px" :src="scope.row.imageUrl" fit="contain"
                    :preview-src-list="imageBox">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间/createTime" width="200" :formatter="formatterTime" />
              <el-table-column prop="updateTime" label="getLastTime/updateTime" width="200"
                :formatter="formatterTime" />
              <el-table-column fixed="right" label="操作" min-width="250">
                <template #default="scope">
                  <el-button link type="primary" v-if="!scope.row.isEdit"
                    @click.prevent="startEdit(scope.$index, scope.row)">
                    修改
                  </el-button>
                  <el-button link type="primary" v-if="scope.row.isEdit"
                    @click.prevent="saveModify(scope.$index, scope.row)">
                    保存
                  </el-button>
                  <el-button link type="primary" v-if="scope.row.isEdit"
                    @click.prevent="cancelEdit(scope.$index, scope.row)">
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 页切换 -->
        <div class="bottom">
          <div class="bottom_left">共有&nbsp;{{ total }}&nbsp;项</div>
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="changePage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { h, onMounted, reactive, ref, toRaw } from 'vue'
import { modifyOperation, reqOperationData } from '@/api/operation';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { getStatus, Status, getNoByStatus } from '@/constant/status';
import { upLoad } from '../../../../api/file';
import { addOperation } from '../../../../api/operation';
import { start } from 'nprogress';

// 加载数据
const initData = async () => {
  operationArr_unprocessed.splice(0, operationArr_unprocessed.length)
  operationArr.splice(0, operationArr.length)
  try {
    let operationRes = await reqOperationData()
    switch (operationRes.code) {
      case 0:
        operationArr.push(...processData(operationRes.data))
        operationArr_unprocessed.push(...operationRes.data)
        total.value = operationRes.data.length
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  }
  catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }
}

// el-dialog
const dialogVisible = ref(false)
const showDialog = () => {
  dialogVisible.value = true
}

// el-table
const startEdit = (idx, row) => {
  row.isEdit = true;
}

// 保存修改
const saveModify = async (idx, row) => {
  let modifyData = {
    id: operationArr_unprocessed[idx].id,
    businessName: row.businessName,
    companyId: row.companyId,
    businessType: operationArr_unprocessed[idx].businessType,
    status: row.status,
    longitude: Number(row.longitude),
    latitude: Number(row.latitude),
    description: row.description,
    path: operationArr_unprocessed[idx].path,
    imageUrl: operationArr_unprocessed[idx].imageUrl,
    component: operationArr_unprocessed[idx].component,
  }
  let res = await modifyOperation(modifyData)
  switch (res.code) {
    case 0:
      ElMessage({
        type: 'success',
        message: '修改成功'
      })
      Object.assign(operationArr[idx], row)
      Object.assign(operationArr_unprocessed[idx], row)
      row.isEdit = false;
      break
    case 1:
      setTimeout(() => { $router.push('/login') }, 1000)
      break
    case 2:
      break
  }
}


const cancelEdit = (idx, row) => {
  Object.assign(operationArr[idx], operationArr_unprocessed[idx])
  row.isEdit = false;
}


// 表格时间格式化
const formatterTime = (row, column) => {
  return row[column.property].substr(0, 10)
}
// 状态转换
const statusMap = (row, column) => {
  return getStatus(row.status)
}
// 当前页号
let pageNo = ref(1)
// 页面大小
let pageSize = ref(10)
// 新建业务表单内容
let addOperationInfo = reactive({
  businessName: null, //业务名称
  companyId: null, //公司Id
  businessType: null, //业务类型（预留字段）
  status: null, //状态（待细化）
  longitude: null,
  latitude: null,
  description: null, //描述
  path: null, //路径
  imageUrl: null, //图片
  component: null, //组件
  cityCode: null
})
// 业务表
let operationArr = reactive([])
// 业务表（未处理）
let operationArr_unprocessed = reactive([])
const processData = (data) => {
  return data.map(item => {
    return {
      ...item,
      isEdit: false,
    }
  })
}
// 表单dom
let formDom = ref()
// 业务总数
let total = ref(0)
// 路由
let $router = useRouter()
// 校验规则
const rules = {
  businessName: [
    { type: "string", required: true, message: '请输入姓名', trigger: ['blur', 'change'] }
  ],
  companyId: [
    { type: "string", required: true, message: '请输入公司id', trigger: ['blur', 'change'] }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: ['blur', 'change'] }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: ['blur', 'change'] }
  ],
  cityCode: [
    { required: true, message: '请输入城市码', trigger: ['blur', 'change'] }
  ],
  description: [
    { type: "string", required: true, message: '请输入描述', trigger: ['blur', 'change'] }
  ],
}

//新建业务确认提交
const addOperationToRemote = async () => {
  let validRes = true
  await formDom.value.validate((valid) => {
    if (!valid) {
      validRes = false
      return false
    }
    return true
  })
  if (!validRes || addOperationInfo.status == null) {
    ElMessage({
      type: "error",
      message: '信息缺漏，请检查'
    })
    return;
  }
  if (addOperationInfo.imageUrl == null) {
    ElMessage({
      type: "error",
      message: '未上传图片'
    })
    return
  }
  addOperationInfo.status = getNoByStatus(addOperationInfo.status)
  addOperationInfo.latitude = Number(addOperationInfo.latitude)
  addOperationInfo.longitude = Number(addOperationInfo.longitude)
  addOperationInfo.cityCode = Number(addOperationInfo.cityCode)
  try {
    let addResult = await addOperation(toRaw(addOperationInfo))
    switch (addResult.code) {
      case 0:
        ElMessage({
          type: 'success',
          message: '添加成功'
        })
        dialogVisible.value = false
        resetForm()
        refresh()
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  }
  catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }

}
// 页面改变(修改)
const changePage = async (newPage) => {
  pageNo.value = newPage
  await initData()
}
// 数据刷新
const refresh = async () => {
  await initData()
}

const resetForm = () => {
  for (let key in addOperationInfo) {
    addOperationInfo[key] = null
  }
}

// 文件上传
const uploadRef = ref(null)


const submitUpload = () => {
  uploadRef.value.submit()
}

const upLoadFile = async (file) => {
  try {
    let res = await upLoad(file)
    switch (res.code) {
      case 0:
        addOperationInfo.imageUrl = res.data
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  } catch (err) {

  }
}

// 上传检查
const uploadPreview = (file) => {
  const isLt5MB = (file.size / 1024 / 1024) < 5;
  if (!isLt5MB) {
    ElMessage({
      type: 'error',
      message: '上传图片不能大于5MB'
    })
    return false;
  };
  return true;
}
onMounted(async () => {
  // 业务列表获取
  await initData()
})
</script>

<style lang="scss" scoped>
input {
  z-index: 0;
}

* {
  box-sizing: border-box;
}

.active {
  color: rgb(24, 148, 197) !important;
}

.hidden {
  display: none !important;
}


.form {
  position: absolute;
  left: 500px;
  top: 200px;
  width: 1200px;
  background-color: #fff;
  color: rgb(156, 153, 153);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 2px 2px 2px rgb(198, 198, 198);

  .formTop {
    border-bottom: 1px solid rgb(207, 202, 202);
    box-sizing: border-box;
    height: 80px;
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 20px;
  }

  .formBody {
    height: 500px;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    margin-bottom: 20px;
    overflow-y: scroll;

    .insideForm {
      margin: 20px;
      display: flex;
      flex-direction: column;
      // align-items: center;
      justify-content: center;

      .upload {
        display: flex;
        justify-content: start;

        .label {
          margin-right: 10px;
          color: gray;
        }
      }
    }
  }

  .formBottom {
    width: 100%;
    height: 50px;
    border-top: 1px solid rgb(207, 202, 202);
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: right;
    padding: 20px;
    box-sizing: border-box;
  }
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;

  .body {
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    color: rgb(156, 153, 153);

    .box {
      margin: 20px;
      width: 85%;
      height: 96%;
      background-color: white;
      padding: 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      border: 1px solid rgb(178, 178, 178);
      box-shadow: 0.5px 0.5px 1px 1px rgb(196, 196, 196);

      .topBtns {
        width: 100%;
        height: 5%;
        font-weight: 700;
        margin-left: 20px;
        display: flex;

        .topBtn {
          flex-grow: 0;
          box-sizing: border-box;
          padding-left: 10px;
          padding-right: 10px;
        }
      }


      .contents {
        margin-top: 10px;
        display: flex;
        box-sizing: border-box;
        width: 100%;
        height: 90%;

        .content {
          height: 100%;
          width: 100%;
          box-sizing: border-box;
          flex-direction: column;
        }
      }

      .bottom {
        display: flex;
        width: 100%;
        margin-top: 20px;
        padding-left: 20px;
        padding-right: 20px;
        box-sizing: border-box;
        // height: 50px;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
}
</style>